//
//  AddNodeViewController.m
//  FDSMeshLibDemo
//
//  Created by LEIPENG on 2022/6/10.
//

#import "AddNodeViewController.h"
#import "SearchDeviceTableViewCell.h"

@interface AddNodeViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) MeshTool *meshTool;
@property (nonatomic, strong) NSString *firmwareFile;
@property (nonatomic, strong) NSString *firmwareVersion;
@property (nonatomic, strong) NSMutableArray *nodeList;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;
@property (weak, nonatomic) IBOutlet UIButton *firmwareButton;
@property (weak, nonatomic) IBOutlet UITableView *tableview;

@end

@implementation AddNodeViewController

#pragma mark - Initialize
- (void)InitializeCode{
    if (FunctionType_AddGroup == self.functionType) {
        self.title = @"组别加灯";
    } else {
        self.title = @"Mesh OTA";
    }
    self.meshTool = [MeshTool shareInstance];
    self.firmwareVersion = @"000060";
    self.firmwareFile = @"";
    if (FirmwareType_NoPa == self.firmwareType) {
        self.firmwareFile = @"LK8620_MESH_GD_v000060_20250611_beta1";
    } else if (FirmwareType_Pa == self.firmwareType) {
        self.firmwareFile = @"LK8720_MESH_GD_v000060_20250611_beta1";
    }
    [self.firmwareButton setTitle:self.firmwareFile.length ? [NSString stringWithFormat:@"固件%@", self.firmwareVersion] : @"暂无固件" forState:(UIControlStateNormal)];
    self.nodeList = [NSMutableArray array];
    self.selectArray = [NSMutableArray array];
    self.confirmButton.layer.cornerRadius = 22;
    self.confirmButton.layer.masksToBounds = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationRefreshNodes) name:FDS_REFRESH_NODES_STATE object:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self InitializeCode];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self notificationRefreshNodes];
}
- (void)notificationRefreshNodes{
    [self.meshTool refreshNodesAndGroups];
    if (FunctionType_AddGroup == self.functionType) {
        [self.nodeList setArray:self.meshTool.nodeListWhitOutGroup];
        // MESH允许设备订阅多个组
        // [self.nodeListWhitOutGroup setArray:self.meshTool.nodeList];
        self.firmwareButton.hidden = YES;
    } else {
        // Mesh OTA支持000058及以上版本的设备
        [self.nodeList removeAllObjects];
        for (FDSMeshNodeModel *model in self.meshTool.nodeList) {
            if (([model.firmwareVersion compare:@"000058"] != NSOrderedAscending)) {
                // 注意：0x00或0xFF代表非PA，0x01代表PA，其它数字代表其它固件类型
                if (FirmwareType_NoPa == self.firmwareType) {
                    if (model.paValue == 0x00 || model.paValue == 0xFF) {
                        [self.nodeList addObject:model];
                    }
                } else if (FirmwareType_Pa == self.firmwareType) {
                    if (model.paValue == 0x01) {
                        [self.nodeList addObject:model];
                    }
                }
            }
        }
        self.firmwareButton.hidden = NO;
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableview reloadData];
    });
}
#pragma mark - UIButton
- (IBAction)clickConfirmBtn:(UIButton *)sender {
    if (self.selectArray.count == 0) {
        [SVProgressHUD showErrorWithStatus:@"未选中设备！"];
    }  else {
        __block NSMutableArray *tempNodeList = [NSMutableArray array];
        NSArray *tempSelectArray = [NSArray arrayWithArray:self.selectArray];
        // 注：此处可以直接把离线的节点过滤掉
        for (NSString *macAddress in tempSelectArray) {
            FDSMeshNodeModel *model = [FDSMeshApi getNodeByMacAddress:macAddress];
            if (model &&
                model.state != FDS_DeviceStateOutOfLine &&
                ![tempNodeList containsObject:model]) {
                [tempNodeList addObject:model];
            }
        }
        if (FunctionType_AddGroup == self.functionType) {
            // 组别加灯
            __block NSInteger progressIndex = 0;
            __block NSInteger failedIndex = 0;
            [SVProgressHUD showProgress:0 status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)tempNodeList.count, (long)failedIndex]];
            FDSMeshGroupModel *groupModel = [FDSMeshApi getGroupByAddress:self.address];
            [FDSMeshApi configSubscribeGroup:tempNodeList groupModel:groupModel isAdd:YES isCompatible:self.meshTool.meshModel.isCompatibleSubscribe progressAction:^(BOOL success, FDSMeshNodeModel * _Nonnull nodeModal) {
                progressIndex++;
                if (!success) {
                    failedIndex++;
                }
                CGFloat progressPercent = (CGFloat)progressIndex/tempNodeList.count;
                [SVProgressHUD showProgress:progressPercent status:[NSString stringWithFormat:@"进度：%ld/%lu，失败：%ld",(long)progressIndex, (unsigned long)tempNodeList.count, (long)failedIndex]];
            } resultAction:^(BOOL finish) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (finish) {
                        [self.meshTool refreshNodesAndGroups];
                        self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                        [self.meshTool codingMeshData:self.meshTool.meshModel];
                        [SVProgressHUD showSuccessWithStatus:@"加组完成"];
                        [self.navigationController popViewControllerAnimated:YES];
                    } else {
                        [SVProgressHUD showErrorWithStatus:@"加组失败！"];
                    }
                });
            }];
        } else {
            // Mesh OTA
            NSString *otaVersion = self.firmwareVersion;
            NSLog(@"Mesh OTA: %@, %@",otaVersion, self.firmwareFile);
            NSData *otaData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:self.firmwareFile ofType:@"bin"]];
            if (self.firmwareFile.length && otaData.length) {
                [SVProgressHUD show];
                // 注：Mesh OTA支持000058及以上版本的设备，否则报错
                [FDSMeshApi startMeshOTAWithOtaData:otaData nodeList:tempNodeList progressAction:^(float progress) {
                    NSLog(@"Mesh OTA Progress ---> %.2f%@",progress *100.0, @"%");
                    [SVProgressHUD showProgress:progress status:[NSString stringWithFormat:@"升级进度：%.2f%@",progress *100.0,@"%"]];
                } resultAction:^(NSArray<NSNumber *> * _Nonnull successAddresses, NSArray<NSNumber *> * _Nonnull failAddresses) {
                    NSLog(@"Mesh OTA Result ---> %@, %@", successAddresses, failAddresses);
                    for (NSNumber *addressValue in successAddresses) {
                        FDSMeshNodeModel *nodeModel = [FDSMeshApi getNodeByAddress:[[NSString stringWithFormat:@"%04lX",(long)addressValue.integerValue] uppercaseString]];
                        if (nodeModel) {
                            [FDSMeshApi renameNode:nodeModel name:nodeModel.name type:nodeModel.type firmwareVersion:otaVersion];
                        }
                    }
                    [self.meshTool refreshNodesAndGroups];
                    self.meshTool.studioModel.meshJson = [FDSMeshApi getCurrentMeshJson];
                    [self.meshTool codingMeshData:self.meshTool.meshModel];
                    NSString *resultTips = [NSString stringWithFormat:@"Mesh OTA升级完成，成功数：%lu，失败数：%lu",(unsigned long)successAddresses.count, (unsigned long)failAddresses.count];
                    NSLog(@"%@", resultTips);
                    [SVProgressHUD showSuccessWithStatus:resultTips];
                } errorAction:^{
                    NSLog(@"Mesh OTA Error");
                    [SVProgressHUD showSuccessWithStatus:@"升级失败"];
                }];
            } else {
                [SVProgressHUD showErrorWithStatus:@"无效的固件，无法升级！"];
            }
        }
    }
}
- (IBAction)clickSelectAllBtn:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.selected) {
        for (FDSMeshNodeModel *nodeModel in self.nodeList) {
            [self.selectArray addObject:nodeModel.macAddress];
        }
    } else {
        [self.selectArray removeAllObjects];
    }
    [self.tableview reloadData];
}
- (IBAction)clickSelectFirmware:(UIButton *)sender {
    UIAlertController *sheetAlert = [UIAlertController alertControllerWithTitle:@"选择固件" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    [sheetAlert addAction:[UIAlertAction actionWithTitle:@"固件000060" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        self.firmwareVersion = @"000060";
        self.firmwareFile = @"";
        if (FirmwareType_NoPa == self.firmwareType) {
            self.firmwareFile = @"LK8620_MESH_GD_v000060_20250611_beta1";
        } else if (FirmwareType_Pa == self.firmwareType) {
            self.firmwareFile = @"LK8720_MESH_GD_v000060_20250611_beta1";
        }
        [self.firmwareButton setTitle:self.firmwareFile.length ? [NSString stringWithFormat:@"固件%@", self.firmwareVersion] : @"暂无固件" forState:(UIControlStateNormal)];
    }]];
    [sheetAlert addAction:[UIAlertAction actionWithTitle:@"固件000061" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        self.firmwareVersion = @"000061";
        self.firmwareFile = @"";
        if (FirmwareType_NoPa == self.firmwareType) {
            self.firmwareFile = @"LK8620_MESH_GD_v000061_20250611_beta1";
        } else if (FirmwareType_Pa == self.firmwareType) {
            self.firmwareFile = @"LK8720_MESH_GD_v000061_20250611_beta1";
        }
        [self.firmwareButton setTitle:self.firmwareFile.length ? [NSString stringWithFormat:@"固件%@", self.firmwareVersion] : @"暂无固件" forState:(UIControlStateNormal)];
    }]];
    [sheetAlert addAction:[UIAlertAction actionWithTitle:@"固件000064" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        self.firmwareVersion = @"000064";
        self.firmwareFile = @"";
        if (FirmwareType_Pa == self.firmwareType) {
            self.firmwareFile = @"LK8720_MESH_GD_v000064_20251118_beta";
        }
        [self.firmwareButton setTitle:self.firmwareFile.length ? [NSString stringWithFormat:@"固件%@", self.firmwareVersion] : @"暂无固件" forState:(UIControlStateNormal)];
    }]];
    [sheetAlert addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {}]];
    if (DEVICE_ISIPAD) {
        sheetAlert.popoverPresentationController.sourceView = self.view;
        sheetAlert.popoverPresentationController.sourceRect = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    [self presentViewController:sheetAlert animated:YES completion:nil];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.nodeList.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SearchDeviceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SearchDeviceTableViewCell class])];
    if (!cell){
        cell = [[NSBundle mainBundle] loadNibNamed:@"SearchDeviceTableViewCell" owner:nil options:nil][0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    FDSMeshNodeModel *nodeModel = self.nodeList[indexPath.row];
    cell.titleLabel.text = nodeModel.name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"%@ - %@", nodeModel.type, nodeModel.macAddress];
    if (nodeModel.state == FDS_DeviceStateOutOfLine) {
        cell.iconImageview.image = [UIImage imageNamed:@"setting_04"];
    } else {
        cell.iconImageview.image = [UIImage imageNamed:@"setting_05"];
    }
    if ([self.selectArray containsObject:nodeModel.macAddress]) {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_02"];
    } else {
        cell.selectImageview.image = [UIImage imageNamed:@"setting_01"];
    }
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FDSMeshNodeModel *nodeModel = self.nodeList[indexPath.row];
    if ([self.selectArray containsObject:nodeModel.macAddress]) {
        [self.selectArray removeObject:nodeModel.macAddress];
    } else {
        [self.selectArray addObject:nodeModel.macAddress];
    }
    [self.tableview reloadData];
}

@end
